#!/bin/bash
source tools/getenv.sh

num=$1
echo "传过来的参数是:"$num

if [[ ! $num =~ ^[0-9]+$ ]]; then
    echo -e "$BOLODRED 传过来的参数必须是一个整数$RESET"
    exit 0
fi

if [[ ! $num -gt 0 ]]; then
  echo -e "$BOLODRED 参数必须是大于0的整数 $RESET"
  exit 0
fi

if [[ "$env" != "test" && "$env" != "prod" ]]; then
  echo -e "$BOLODRED $env 环境，不支持回滚 $RESET"
  exit 0
fi


keep_backups=10
if [[ "$env" == "dev" ]]; then
  keep_backups=2
elif [[ "$env" == "test" ]]; then
  keep_backups=5
elif [[ "$env" == "prod" ]]; then
  keep_backups=10
fi

if [[ $num -gt $keep_backups ]]; then
  echo -e "$BOLODRED 参数超过了当前环境 $env 最大的备份上限 $keep_backups $RESET"
  exit 0
fi


function rollbackn() {
      # 获取备份文件的个数
      backup_count=$(ls -1d "${real_app_root_path}.backup-"* 2>/dev/null | wc -l)

      # 如果没有备份文件或者备份文件没有n个，直接退出
      if [[ $backup_count -lt $num ]]; then
        echo -e "$BOLODRED 没有备份文件,退出 $RESET"
        exit 0
      fi


      # 获取到最近的一个备份文件
      neet_backup=$(ls -1dr "${real_app_root_path}.backup-"* 2>/dev/null | head -n "$num" | tail -n 1)
      if [[ ! -e $neet_backup ]]; then
        echo -e "$BOLODRED 找不到第 $num 个备份文件 $RESET"
        exit 0
      fi

      echo "neet_backup = $neet_backup"
      echo "current_dir = $current_dir"
      # 把当前的软连指向这个
      if [[ -e "${current_dir}.bak" ]]; then
        echo -e "$GREEN ${current_dir}.bak 已经存在, 删除... $RESET"
        rm -rf "${current_dir}.bak"
        echo "删除成功"
      fi

      rollbackStr="cd .. && rm -rf $current_dir && mv ${current_dir}.bak ${current_dir}"
      echo "mv $current_dir ${current_dir}.bak"
      mv "$current_dir" "${current_dir}.bak"
      echo "cd .. && ln -sf $neet_backup $app_root_path"
      cd .. && ln -sf "$neet_backup" "$app_root_path"
      ls -all "$current_dir"
      echo -e "$BOLODGREEN 回滚成功,后续请手动指向最新目录, 或者运行 make rollbackback $RESET"

      rollbackAfterRestart

      echo "回滚命令："
      echo -e "$BOLODGREEN $rollbackStr $RESET"
      echo ""

}

rollbackn

echo "回滚指定备份完成"
